package com.bourse.core.ibatisHandler;

import java.sql.SQLException;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

/**
 * Simple IBatis type handler callback which will map a String to a Boolean.
 * <ul>
 * <li>"Y" : true</li>
 * <li>"N" : false</li>
 * <li>anything else : false</li>
 * </ul>
 */
public class YesNoBooleanTybeHandlerCallback implements TypeHandlerCallback {

	private static final String YES = "Y";

	private static final String NO = "N";

	/**
	 * Extract the String from given value, and see if it contains 'Y' or 'N'.
	 *
	 * @param getter The interface for getting the value from the ResultSet.
	 * @return true if extracted String equals 'Y', false otherwise.
	 * @throws SQLException If any error occurs.
	 */
	public Object getResult(ResultGetter getter) throws SQLException {
		String s = getter.getString();

		if (getter.wasNull()) {
			return null;
		}

		return YES.equalsIgnoreCase(s) ? Boolean.TRUE : Boolean.FALSE;
	}

	/**
	 * Transform the given Boolean (parameter) into a String representation and push it in the given setter.
	 *
	 * @param setter
	 * @param parameter
	 * @throws SQLException
	 */
	public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
		if (parameter == null) {
			setter.setString(null);
		} else {
			final boolean b = ((Boolean) parameter).booleanValue();
			if (b) {
				setter.setString(YES);
			} else {
				setter.setString(NO);
			}
		}
	}

	/**
	 * Transform the given String into a Boolean.
	 *
	 * @param string
	 * @return userId object
	 */
	public Object valueOf(String string) {
		if (string == null) {
			return null;
		}

		return YES.equalsIgnoreCase(string) ? Boolean.TRUE : Boolean.FALSE;
	}

}
